package im

import (
	"fmt"
	"time"
	"strings"
	"dhfshop/models/isv"
	"github.com/astaxie/beego"
	"github.com/pkg/errors"
	"wxsdk/miniapp/message/callback/response"
	"wxsdk/miniapp/utils/security"
	"wxsdk/oauth"
	"wxsdk/miniapp/message/custom/public"
)

func AutoReplyWholeTest(isvToken,isvAESKey,isvAppId string,reqMap map[string]string,ctrl *beego.Controller) {
	now := time.Now()
	msgType := getTestMsgType(reqMap)
	if msgType == 0 {
		beego.Emergency("msgType is error: ")
		return
	}
	//响应事件推送消息(被动回复消息，需要加密)
	if msgType == 1 {
		timestamp := now.Unix()
		content := fmt.Sprintf("%s%s", reqMap["Event"], "from_callback")
		text := response.NewText(reqMap["FromUserName"], reqMap["ToUserName"], timestamp, content)
		msgXml, err := security.EncrypterStruct(isvToken,isvAESKey,isvAppId,*text)
		if err != nil {
			beego.Emergency(err.Error())
			return
		}
		ctrl.Ctx.Output.Body(msgXml)    // this.Ctx.WriteString("") ???
	}
	//回复文本消息(被动回复消息，需要加密)
	if msgType == 2 {
		timestamp := now.Unix()
		content := fmt.Sprintf("%s%s", reqMap["Content"], "_callback")
		text := response.NewText(reqMap["FromUserName"], reqMap["ToUserName"], timestamp, content)
		msgXml, err := security.EncrypterStruct(isvToken,isvAESKey,isvAppId,*text)
		if err != nil {
			beego.Emergency(err.Error())
			return
		}
		ctrl.Ctx.Output.Body(msgXml)
	}
	//调用微信api回复文本消息(客服API消息，不需要加密)
	if msgType == 3 {
		authorize, err := isv.GetAuthorizeByAppId(isvAppId)
		if err != nil {
			err = errors.Wrap(err, "GetAuthorizeByAppId... ")
			beego.Emergency(err.Error())
			return
		}
		contents := strings.Split(reqMap["Content"], ":")
		authorizationCode := contents[1]
		tokenInfo, err := oauth.ApiQueryAuth(isvAppId,authorize.AccessToken,authorizationCode)
		if err != nil {
			err = errors.Wrap(err, "ApiQueryAuth... ")
			beego.Emergency(err.Error())
			return
		}
		content := fmt.Sprintf("%s%s", authorizationCode, "_from_api")
		public.SendTextMessage(tokenInfo.AuthorizationInfo.AccessToken, reqMap["FromUserName"], content)
		ctrl.Ctx.Output.Body([]byte(""))
	}
}

func getTestMsgType(reqMap map[string]string) (msgType int) {
	switch reqMap["MsgType"] {
	case "event":
		msgType = 1
	case "text":
		if strings.HasPrefix(reqMap["Content"], "QUERY_AUTH_CODE") {
			msgType = 3
		} else {
			msgType = 2
		}
	}
	return
}
